package com.springboot.fram.core.system;

import com.springboot.fram.core.enums.SystemType;
import org.apache.commons.lang3.StringUtils;
import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;

/**
 * Java的System类封装工具类。
 *
 * @author Looly
 */
public final class SystemUtils {
  /**
   * 获取当前进程 PID
   *
   * @return 当前进程 ID
   */
  public static long getCurrentPID() {
    return Long.parseLong(ManagementFactory.getRuntimeMXBean().getName().split("@")[0]);
  }

  /**
   * 获取系统类型(window、linux等)
   */
  public static String getSystemOS() {
    return System.getProperty("os.name");
  }

  /**
   * 获取本机局域网ip
   */
  public static InetAddress getLocalIp() {
    String osName = getSystemOS();
    // 针对window系统
    if (StringUtils.containsIgnoreCase(osName, SystemType.WINDOWS.name())) {
      try {
        return InetAddress.getLocalHost();
      } catch (UnknownHostException e) {
        return null;
      }
    }
    // 针对linux系统
    if (StringUtils.containsIgnoreCase(osName, SystemType.LINUX.name())) {
      return getUnixLocalIp();
    }
    return null;
  }

  private static InetAddress getUnixLocalIp() {
    try {
      Enumeration<?> netInterfaces = NetworkInterface.getNetworkInterfaces();
      while (netInterfaces.hasMoreElements()) {
        NetworkInterface ni = (NetworkInterface) netInterfaces.nextElement();
        InetAddress ip = ni.getInetAddresses().nextElement();
        if (!ip.isSiteLocalAddress() && !ip.isLoopbackAddress()
            && !ip.getHostAddress().contains(":")) {
          return ip;
        }
      }
      return null;
    } catch (SocketException e) {
      return null;
    }
  }

}
